/*
 * @lc app=leetcode.cn id=795 lang=typescript
 *
 * [795] 区间子数组个数
 */

// @lc code=start
function numSubarrayBoundedMax(nums: number[], left: number, right: number): number {
  let ans = 0;
  // 右边界
  let last1 = -1;
  // 左边界
  let last2 = -1;
  for (let i = 0; i < nums.length; i++) {
    // 合法的右边界
    if (nums[i] >= left && nums[i] <= right) {
      last1 = i;
    } else if (nums[i] > right) {
      // 左边界变更，重新寻找右边界
      last2 = i;
      last1 = -1;
    }
    // 更新答案
    if (last1 !== -1) {
      ans += last1 - last2;
    }
  }

  return ans;
}
// @lc code=end
